<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>滚动加载演示</title>
  <style>
  body,html{
    margin:0px;
    height:0px;
  }

  .container{
    width:100%;
    height:calc( 100vh );
  }

  .container1{
    position: fixed;
    right:100px;
    top:100px;
    width:200px;
    height:500px;
  }

  .item {
    height:200px;
    font-size:20px;
    color:#000;
  }

  .item:nth-of-type(2n-1){
    background-color: #CCCCCC;
  }

  .item:nth-of-type(2n){
    background-color: #E5E5E5;
  }

  .item.t2:nth-of-type(2n-1){
    background-color: #7b81da;
  }

  .item.t2:nth-of-type(2n){
    background-color: #9a7eb1;
  }

  .tip{
    position: fixed;
    right:0px;
    top:0px;
    color:#FF0000;
    font-size:20px;
  }
  </style>
</head>
<body>
  <div class="container" id="test1">

  </div>
  <div class="container1" id="test2">

  </div>
  <script>

window.addEventListener('touchmove', function(e) {
	e.preventDefault();
}, { passive: false });

  let index=5  // mock
  let index1=5 

  let sel1=new hScroll({
    el:document.getElementById('test1'),
    load:function(){
      // mock ajax
      setTimeout(()=>{
        let html=''
        for (let i=index+1;i<index+6;i++){
          html+=`
          <div class="item">
            第${i}个
          </div>
          `
        }
        index+=5
        this.finish(html)
      },200)
    }
  })

  let sel2=new hScroll({
    el:document.getElementById('test2'),
    load:function(){
      // mock ajax
      setTimeout(()=>{
        let html=''
        for (let i=index1+1;i<index1+6;i++){
          html+=`
          <div class="item t2">
            第${i}个
          </div>
          `
        }
        index1+=5
        this.finish(html)
      },200)
    }
  })

  function hScroll(cfg){
    if (cfg.el===void 0){
      console.error('hScoll needs a dom to create')
    }

    let obj={
      el:document.getElementsByTagName('body')[0],
      dis:10,
      load:function(){
      },
      lock:false,
      finish:function(html){
        this.wra.innerHTML+=html
        this.lock=false
      }
    }

    for (let key of Object.keys(cfg)){
      if (cfg[key]!==void 0){
        obj[key]=cfg[key]
      }
    }

    obj.el.style.overflow='auto'
    obj.el.innerHTML=''
    let wraDom=document.createElement('div')
    wraDom.className='wrapper'
    obj.wra=wraDom
    obj.el.appendChild(wraDom)
    

    obj.el.addEventListener('scroll',function(){
      let nowDis=obj.wra.offsetHeight-obj.el.scrollTop-obj.el.offsetHeight

      if (nowDis<=obj.dis && obj.lock===false){

        obj.lock=true
        obj.load()
      }
    })

    obj.load()

    return obj
  }


  </script>
</body>
</html>